package com.hyj.serve.manage.controller;

import com.hyj.serve.manage.configure.exception.ServiceException;
import com.hyj.serve.manage.entity.HostEntity;
import com.hyj.serve.manage.service.HostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;

import javax.servlet.http.HttpServletRequest;

/**
 * @author HeYuJie
 * @date 2022/6/7
 */
public abstract class HostControllerWidget {

    public static final String HOST_ID_KEY = "host_id";
    public static final String HOST_ID_ENTITY = "host_entity";

    @Autowired
    private HostService hostService;

    @Autowired
    private HttpServletRequest request;

    @ModelAttribute
    public void executeBefore(@PathVariable("hostId") Integer hostId, HttpServletRequest request) {
        request.setAttribute(HOST_ID_KEY, hostId);

        HostEntity hostEntity = hostService.getById(hostId);

        request.setAttribute(HOST_ID_ENTITY, hostEntity);
        if (hostEntity == null) {
            throw new ServiceException("没有这个主机 => " + hostId);
        }
    }

    protected Integer getHostId(){
        return (Integer) request.getAttribute(HOST_ID_KEY);
    }

    protected HostEntity getHost(){
        return (HostEntity) request.getAttribute(HOST_ID_ENTITY);
    }

}
